<template>
  <div class="info-view">
    <el-row>
      <el-form ref="form" :model="form" size="small" class="spider-form" label-width="80px;padding: 10px 0;">
        <!-- 资源配置-->
        <el-form-item>
          <el-tag type="warning">资源配置</el-tag>
        </el-form-item>
        <el-row>
          <el-col :span="4">
            <el-form-item label="资源规格">
              <el-select
                v-model="form.s"
                filterable
                placeholder="请选择"
                style="width: 110px;"
                @change="standardChange"
              >
                <el-option
                  v-for="item in resourceList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="实例数量">
              <el-input-number v-model.number="form.replicas" :min="0" :max="80" controls-position="right" style="width: 178px;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="最低分配CPU" prop="requestCpu">
              <el-select v-model="form.resource.requests.cpu" filterable allow-create placeholder="请选择" style="width: 110px;">
                <el-option
                  v-for="item in dict.cpu_spec"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="最低分配内存" prop="requesMem">
              <el-select v-model="form.resource.requests.memory" filterable allow-create placeholder="请选择" style="width: 110px;">
                <el-option
                  v-for="item in dict.memory_spec"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="CPU使用限制" prop="limitsCpu">
              <el-select v-model="form.resource.limits.cpu" filterable allow-create placeholder="请选择" style="width: 110px;">
                <el-option
                  v-for="item in dict.cpu_spec"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="内存使用限制" prop="limitsMem">
              <el-select v-model="form.resource.limits.memory" filterable allow-create placeholder="请选择" style="width: 110px;">
                <el-option
                  v-for="item in dict.memory_spec"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item></el-col>
        </el-row>
        <!-- 心跳配置-->
        <el-divider />
        <el-form-item>
          <el-tag type="warning">心跳配置</el-tag>
        </el-form-item>
        <el-row>
          <el-col :span="6">
            <el-form-item label="存活检测时间(秒)" prop="livenessDelaySeconds">
              <el-input v-model="form.healthcheck.livenessDelaySeconds" type="number" style="width: 100px;" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="就绪检测时间(秒)" prop="readinessDelaySeconds">
              <el-input v-model="form.healthcheck.readinessDelaySeconds" type="number" style="width: 100px;" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检测间隔时间(秒)" prop="periodSeconds">
              <el-input v-model="form.healthcheck.periodSeconds" type="number" style="width: 110px;" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="心跳地址" prop="path">
              <el-input v-model="form.healthcheck.path" style="width: 170px;" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 端口配置 -->
        <el-divider />
        <el-form-item>
          <el-tag type="warning">端口配置</el-tag>
        </el-form-item>
        <el-row v-for="(domain, index) in form.ports" :key="index">
          <el-col :span="6">
            <el-form-item label="名称" :prop="'ports.' + index + '.name'" :rules="rules.name">
              <el-input v-model="domain.name" style="width: 120px;" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="端口" :prop="'ports.' + index + '.containerPort'">
              <el-input v-model="domain.containerPort" type="number" style="width: 180px;" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="协议" :prop="'ports.' + index + '.protocol'">
              <el-input v-model="domain.protocol" style="width: 180px;" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <el-button type="danger" icon="el-icon-delete" circle @click="deleteItemInArray(domain, index, form.ports)" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="text" @click="addPort">新增端口配置</el-button>
        </el-form-item>
        <!-- 存储配置 -->
        <el-divider />
        <el-form-item>
          <el-tag type="warning">存储配置</el-tag>
        </el-form-item>
        <el-row v-for="(domain, index) in form.volumes" :key="domain.key">
          <el-col :span="7">
            <el-form-item label="别名" :prop="'volumes.' + index + '.name'" :rules="rules.name">
              <el-input v-model="domain.name" style="width: 150px;" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="存储名称(集群)" :prop="'volumes.' + index + '.claimName'" :rules="rules.name">
              <el-input v-model="domain.claimName" style="width: 200px;" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <el-button type="danger" icon="el-icon-delete" circle @click="deleteItemInArray(domain, index, form.volumes)" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="text" @click="addVolume">新增存储配置</el-button>
        </el-form-item>
        <!-- 挂载配置 -->
        <el-divider />
        <el-form-item>
          <el-tag type="warning">挂载配置</el-tag>
        </el-form-item>
        <el-row v-for="(domain, index) in form.volumeMounts" :key="domain.key">
          <el-col :span="5">
            <el-form-item label="别名" :prop="'volumeMounts.' + index + '.name'" :rules="rules.name">
              <el-input v-model="domain.name" style="width: 120px;" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="容器路径" :prop="'volumeMounts.' + index + '.mountPath'" :rules="rules.name">
              <el-input v-model="domain.mountPath" style="width: 120px;" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="磁盘路径" :prop="'volumeMounts.' + index + '.subPathExpr'">
              <el-input v-model="domain.subPathExpr" style="width: 120px;" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="只读" :prop="'volumeMounts.' + index + '.readOnly'">
              <el-switch
                v-model="domain.readOnly"
                active-color="#409EFF"
                inactive-color="#F56C6C"
              />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item>
              <el-button type="danger" icon="el-icon-delete" circle @click="deleteItemInArray(domain, index, form.volumeMounts)" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="text" @click="addVolumeMount">新增挂载配置</el-button>
        </el-form-item>
      </el-form>
    </el-row>

    <el-row>
      <el-button
        size="small"
        type="primary"
        icon="el-icon-check"
        @click="doSaveServerDeployParam('form')"
      >
        保存
      </el-button>
    </el-row>
  </div>
</template>

<script>

import { mapGetters } from 'vuex'
import * as APIS from '@/api/server'
import { Notification } from 'element-ui'
import { saveOrUpdate2 as paramSaveOrUpdate } from '@/api/deploy/dpServerConfig'
import { getAll as getAllResource, findById } from '@/api/deploy/dpResourceStandards'

export default {
  name: 'DpServerDeployConfig2',
  dicts: ['cpu_spec', 'memory_spec'],
  components: { },
  props: {
    projectId: {
      type: Number,
      default: () => { return -1 }
    }
  },
  data() {
    return {
      rules: {
        name: [{ required: true, message: '请输入一个值', trigger: 'blur' }]
      },
      resourceList: [],
      form: {
        projectId: this.projectId,
        env: this.env,
        s: '',
        resource: {
          requests: { cpu: '200m', memory: '512Mi' },
          limits: { cpu: '2000m', memory: '2Gi' }
        },
        healthcheck: { livenessDelaySeconds: 60, readinessDelaySeconds: 77, periodSeconds: 10, path: '/version.txt' },
        ports: [{ name: '', containerPort: '', protocol: '' }],
        volumes: [{ name: '', claimName: '' }],
        volumeMounts: [{ name: '', mountPath: '', subPathExpr: '', readOnly: false }]
      }
    }
  },
  computed: {
    ...mapGetters([
      'env'
    ])
  },
  watch: {
  },
  created() {
    // 监听应用下拉框选择事件
    this.$bus.$on('global-env-change', this.reloadData)
  },
  mounted() {
    this.reloadData()
    this.getResourceList()
  },
  methods: {
    standardChange(id) {
      findById(id).then(data => {
        if (data != null) {
          this.form.resource.requests.cpu = data.minCpu
          this.form.resource.requests.memory = data.minMemory
          this.form.resource.limits.cpu = data.maxCpu
          this.form.resource.limits.memory = data.maxMemory
        }
      })
    },
    deleteItemInArray(item, index, array) {
      this.index = array.indexOf(item)
      if (index !== -1) {
        array.splice(index, 1)
      }
    },
    getResourceList() {
      getAllResource().then(data => {
        this.resourceList = data
      })
    },
    addPort() {
      this.form.ports.push({ name: '', containerPort: '', protocol: 'TCP' })
    },
    addVolume() {
      this.form.volumes.push({ name: '', claimName: '' })
    },
    addVolumeMount() {
      this.form.volumeMounts.push({ name: '', mountPath: '', subPathExpr: '', readOnly: false })
    },
    doSaveServerDeployParam(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          paramSaveOrUpdate(this.form).then(res => {
            Notification.success({ title: '保存成功', duration: 1000 })
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    initEmptyData() {
      this.form = {
        projectId: this.projectId,
        env: this.env,
        resource: {
          requests: { cpu: '', memory: '' },
          limits: { cpu: '', memory: '' }
        },
        healthcheck: {
          livenessDelaySeconds: 60,
          readinessDelaySeconds: 60,
          periodSeconds: 10,
          path: '/version.txt'
        },
        ports: [],
        volumes: [],
        volumeMounts: []
      }
    },
    reloadData() {
      this.queryLoading = true
      return APIS.getServerConfigByProjectIdAndEnv({
        projectId: this.projectId,
        env: this.env
      }).then(res => {
        if (res == null || res === '') {
          Notification.error({
            title: '部署参数值未配置',
            duration: 2000
          })
          this.initEmptyData()
          return
        }
        const deployParamJsonStr = res.deployParam
        if (deployParamJsonStr == null || deployParamJsonStr === '') {
          this.initEmptyData()
        } else {
          this.form = JSON.parse(deployParamJsonStr)
        }
        this.form.projectId = this.projectId
        this.form.env = this.env
      }).catch(err => {
        Notification.error({
          title: err,
          duration: 2000
        })
        this.initEmptyData()
      }).finally(() => {
        this.queryLoading = false
      })
    }
  }
}
</script>

<style scoped>
  .spider-form {
    padding: 10px;
  }

  .button-container {
    padding: 0 10px;
    width: 100%;
    text-align: right;
  }

  .el-autocomplete {
    width: 100%;
  }

  .info-view > > > .el-upload-list {
    display: none;
  }

  .el-divider--horizontal {
    margin-bottom: 15px;
    marigin-top: 10px;
  }

  .button-group {
    width: 100%;
    text-align: left;
    margin-top: 15px;
    margin-bottom: 0px;
    margin-left: 12px;
  }
</style>
